package com.regex.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.regex.web.cache.DictCacheService;
import com.regex.web.entity.sys.MenuDTO;
import com.regex.web.entity.sys.RoleMenuDTO;
import com.regex.web.entity.sys.UserDTO;
import com.regex.web.entity.sys.UserRoleDTO;
import com.regex.web.service.sys.IMenuService;
import com.regex.web.service.sys.IRoleMenuService;
import com.regex.web.service.sys.IUserRoleService;
import com.regex.web.utils.Assist;
import com.regex.web.utils.SaveUploadFile;
import com.regex.web.vo.ImageVO;
import com.regex.web.vo.ResultVO;

@Controller
public class IndexController {
	
	private final static Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	@Value("${picUrlHost}")
	private String picUrlHost;
	
	@Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleMenuService roleMenuService;

    @Autowired
    private IMenuService menuService;
	
	@Autowired
	private SaveUploadFile SaveUploadFile;
	
	@Autowired
	private DictCacheService dictCacheService;
	
//	@Autowired
//    private OssManage ossManage;
	
	@RequestMapping("/index")
	public String index(HttpServletRequest request) {
		LinkedHashMap<String, Object> dictMap = (LinkedHashMap<String, Object>) request.getSession().getAttribute("dictMap");
        if(dictMap == null || dictMap.size() == 0) {
            dictMap = dictCacheService.getDictCache();
        	request.getSession().setAttribute("dictMap", dictMap);
        	System.out.println("=================");
        }
		return "index";
	}
	
	@RequestMapping("/ckeditor")
	public String ckeditor() {
		return "ckeditor/index";
	}
	
	@RequestMapping("/")
    public String defaultIndex() {
        return "redirect:main";
    }
	
	@PostMapping("cleanCache")
	@ResponseBody
	public ResultVO<String> cleanCache(HttpServletRequest request) {
		dictCacheService.setLongTime(0l);
		request.getSession().removeAttribute("dictMap");
		return ResultVO.success();
	}
	
	/**
     * 
     * 功能描述: <br>
     * 系统主界面
     *
     * @param model
     * @param request
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("main")
    public String main(Model model, HttpServletRequest request) {
        try {
            PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
            UserDTO user = (UserDTO) principals.getPrimaryPrincipal();
            Assist assist = new Assist();
        	assist.setRequires(Assist.andEq("user_id", user.getId()));
            List<UserRoleDTO> userRoleList = userRoleService.selectUserRoleDTO(assist);
            List<RoleMenuDTO> roleMenuDTOList = new ArrayList<RoleMenuDTO>();
            for(UserRoleDTO userRoleDTO : userRoleList) {
            	Assist assist2 = new Assist();
            	assist2.setRequires(Assist.andEq("role_id", userRoleDTO.getRoleId()));
            	List<RoleMenuDTO> list = roleMenuService.selectRoleMenuDTO(assist2);
                roleMenuDTOList.addAll(list);
            }
            Map<Long, Object> map = new LinkedHashMap<Long, Object>();
            for (RoleMenuDTO roleMenu : roleMenuDTOList) {
                map.put(roleMenu.getMenuId(), "1");
            }
            // 获取菜单并设置session
            @SuppressWarnings("unchecked")
            List<MenuDTO> menuList = (List<MenuDTO>) request.getSession().getAttribute("menuList");
            if(menuList == null || menuList.size() == 0) {
                menuList = getMenuList(0, map);
                request.getSession().setAttribute("menuList", menuList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "main";
    }
    
    /**
     * 
     * 功能描述: <br>
     * 
     *  遍历获取菜单 不获取按钮。只获取目录和菜单
     * @param parent
     * @param map
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<MenuDTO> getMenuList(long parent, Map<Long, Object> map) {
        Assist assist = new Assist();
    	assist.setRequires(Assist.andEq("is_del", "0"));
    	assist.setRequires(Assist.andEq("parent_id", parent));
    	assist.setRequires(Assist.andNeq("type", "2"));
    	assist.setOrder(Assist.order("order_num ", true));
        List<MenuDTO> menuTmpList = menuService.selectMenuDTO(assist);
        List<MenuDTO> menuList = null;
        if(null != menuTmpList && menuTmpList.size() != 0) {
            menuList = new ArrayList<MenuDTO>();
            for (MenuDTO menu : menuTmpList) {
                if (null != map.get(menu.getId())) {
                    List<MenuDTO> childMenuList = getMenuList(menu.getId(), map);
                    if (null != childMenuList && childMenuList.size() != 0) {
                        menu.setChildMenu(childMenuList);
                    }
                    menuList.add(menu);
                }
            }
        }
        return menuList;
    }
    
    /**
     * 
     * 功能描述: <br>
     * 上传图片
     *
     * @param file
     * @param response
     * @param request
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "uploadImage", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImage(MultipartFile file, HttpServletResponse response,
	        HttpServletRequest request) {
 		String fileName=file.getOriginalFilename();
		String fileNameArray[] = fileName.split("\\.");
		fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileNameArray[fileNameArray.length - 1];
		String url = "";
		try {
			// 上传到相对路径（服务器目录下）可直接带域名访问
//		    url = SaveUploadFile.savePic(file, request, fileName, "");
		    // 上传到配置的绝对路径下
		    url = SaveUploadFile.saveTruePic(file, request, fileName, "");
		} catch (Exception e) {
		    e.printStackTrace();
			logger.error("upload is fail!");
		}
		logger.error(url);
		ImageVO imageVO = new ImageVO();
		imageVO.setImageName(fileName);
		imageVO.setImageUrl(url);
		imageVO.setImageShowUrl(picUrlHost + url);
		String s = JSON.toJSONString(imageVO);
		System.out.println(s);
		return s;
	}
    
    /**
     * 
     * 功能描述: <br>
     * ckeditor 文件上传
     *
     * @param file
     * @param response
     * @param request
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "ckeditorUploadImage", method = RequestMethod.POST)
    @ResponseBody
    public String ckeditorUploadImage(MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        String oldFileName = file.getOriginalFilename();
        String fileNameArray[] = oldFileName.split("\\.");
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileNameArray[fileNameArray.length - 1];
        String url = "";
        try {
             url = SaveUploadFile.savePic(file, request, fileName, "");
//            ossManage.SaveUploadFile(file, fileName, "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("upload is fail!");
        }
//        url = ossManage.getIpaURl(fileName);
        if (StringUtils.isNotEmpty(url)) {
            String urlArr[] = url.split("\\?");
            url = urlArr[0];
        }
        
        String mimeType = request.getServletContext().getMimeType(oldFileName);
        
        logger.error(url);
        ImageVO imageVO = new ImageVO();
        imageVO.setImageName(fileName);
        imageVO.setImageUrl(url);
        imageVO.setImageShowUrl(url);
        if (mimeType.startsWith("image/")) {
            imageVO.setFileType("img");
        } else {
            imageVO.setImageName(oldFileName);
            imageVO.setFileType("file");
        }
        // 返回附件id
        ResultVO<ImageVO> res = new ResultVO<ImageVO>(ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
        res.setData(imageVO);
        String s = JSON.toJSONString(res);
        return s;
    }
    
    @PostMapping(value = "uploadBase64Images")
    @ResponseBody
    public ResultVO<List<ImageVO>> uploadBase64Images(@RequestBody List<String> imgArray, HttpServletResponse response, HttpServletRequest request) {
        List<ImageVO> imgList = new ArrayList<ImageVO>();
        for(String base64Img : imgArray) {
                // String key = "";
         // 使用前端插件时可能有前有（"data:image/xxxx;base64,"）
            // 获取图片格式
            String suffix = base64Img.substring(11,base64Img.indexOf(";"));
            // 使用插件传输产生的前缀
            String prefix = base64Img.substring(0,base64Img.indexOf(",") + 1);
            // 替换前缀为空
            base64Img = base64Img.replace(prefix,"");
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
            String url = "";
                try {
                    url = SaveUploadFile.savePic(base64Img, request, fileName, "");
//                    key = ossManage.upload(base64Img, "");
                } catch (Exception e) {
                    logger.error("upload is fail!");
                }
                
//                String url = ossManage.getIpaURl(key);
//                if (StringUtils.isNotEmpty(url)) {
//                    String urlArr[] = url.split("\\?");
//                    url = urlArr[0];
//                }
                logger.error(url);
                ImageVO imageVO = new ImageVO();
                imageVO.setImageName(fileName);
                imageVO.setImageUrl(url);
                imgList.add(imageVO);
        }
        return ResultVO.success(imgList, ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
    
    /**
     * 
     * 功能描述: <br>
     * 富文本上传图片
     *
     * @param file
     * @param response
     * @param request
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "textUploadImage", method = RequestMethod.POST)
    @ResponseBody
    public String textUploadImage(MultipartFile file, HttpServletResponse response,
            HttpServletRequest request) {
        String fileName=file.getOriginalFilename();
        UUID.randomUUID();
        String fileNameArray[] = fileName.split("\\.");
        fileName = UUID.randomUUID() + "." + fileNameArray[fileNameArray.length - 1];
        String url = "";
        try {
            url = SaveUploadFile.savePic(file, request, fileName, "");
        } catch (Exception e) {
            logger.error("upload is fail!");
        }
        logger.error(url);
        ImageVO imageVO = new ImageVO();
        imageVO.setImageName(fileName);
        imageVO.setImageUrl(url);
        Map<String,Object> map = new HashMap<String,Object>();

        Map<String,Object> map2 = new HashMap<String,Object>();
        map.put("code",0);//0表示成功，1失败
        map.put("msg","上传成功");//提示消息
        map.put("data",map2);
        map2.put("src",url);//图片url
        map2.put("title",fileName);//图片名称，这个会显示在输入框里
        String result = new JSONObject(map).toString();

        System.out.println(result);
        return result;
    }
    
    
    @RequestMapping(value = "uploadBase64Image", method = RequestMethod.POST)
    @ResponseBody
    public String uploadBase64Images(String base64Img, String fileName, HttpServletResponse response, HttpServletRequest request) {
//            String fileName=fileField.getOriginalFilename();
        int delLength = base64Img.indexOf(',') + 1;  
        String str = base64Img.substring(delLength, base64Img.length() - delLength);    
            UUID.randomUUID();
            String fileNameArray[] = fileName.split("\\.");
            fileName = UUID.randomUUID() + "." + fileNameArray[fileNameArray.length - 1];
            String url = "";
            try {
                url = SaveUploadFile.savePic(str, request, fileName, "");
            } catch (Exception e) {
            	logger.error("upload is fail!");
            }
            logger.error(url);
            ImageVO imageVO = new ImageVO();
            imageVO.setImageName(fileName);
            imageVO.setImageUrl(url);
//            imageList.add(imageVO);
        String s = JSON.toJSONString(imageVO);
        return s;
    }

}
